package com.eet.juc.fork;

import java.util.concurrent.RecursiveTask;

/**
 * 分治线程任务
 * 如何使用ForkJoin
 * 1. ForkJoinPool通过execute或者submit来执行
 * 2. 计算类要继承ForkJoinTask
 *
 * @author zheng.zhang
 */
public class SumTask extends RecursiveTask<Long> {
    private Long start;
    private Long end;

    public SumTask(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long temp = 10000L;
        if ((end - start) < temp) {
            long sum = 0;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }
        long middle = (start + end) / 2;
        SumTask task1 = new SumTask(start, middle);
        // 拆分任务,把任务压入线程队列
        task1.fork();
        SumTask task2 = new SumTask(middle + 1, end);
        task2.fork();
        return task1.join() + task2.join();
    }
}
